import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
  selector: 'app-todo-header',
  templateUrl: './todo-header.component.html',
  styleUrls: ['./todo-header.component.css']
})
export class TodoHeaderComponent implements OnInit {
  inputValue: string = '';
  // placeholder和delay作为2个输入型变量，这样<app-todo-header>标签中就可以设置这两个属性了
  @Input() placeholder: string = 'what needs to be done?';
  @Input() delay: number = 300;

  // 事件发射器
  @Output() textChanges = new EventEmitter<string>();
  @Output() onEnterUp = new EventEmitter<boolean>();

  constructor(private elementRef: ElementRef) {
    // ElementRef，这个是一个Angular中需要谨慎使用的对象，因为它可以让你直接操作DOM，也就是HTML的元素和事件
    const event$ = Observable.fromEvent(elementRef.nativeElement, 'keyup')
      .map(() => this.inputValue)
      .debounceTime(this.delay)// 滤波器
      .distinctUntilChanged();// 筛选器

    event$.subscribe(input => {
      this.textChanges.emit(input)
    });
  }

  ngOnInit() {
  }

  enterUp() {
    if (this.inputValue == '') {
      return;
    }
    this.onEnterUp.emit(true);
    this.inputValue = '';
  }
}
